package com.yfp.auth.controller;

import com.yfp.auth.form.LoginBody;
import com.yfp.auth.form.RegisterBody;
import com.yfp.auth.form.ResetBody;
import com.yfp.auth.service.SysLoginService;
import com.yfp.common.core.domain.R;
import com.yfp.common.core.utils.sign.RsaUtils;
import com.yfp.common.security.service.TokenService;
import com.yfp.system.api.model.LoginUser;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 用户登录相关
 *
 * 
 * @date 2023/12/07
 */
@Tag(name = "用户登录相关")
@RestController
public class AccountController {

    @Resource
    private TokenService tokenService;

    @Resource
    private SysLoginService sysLoginService;


    @Operation(summary = "用户注册")
    @PostMapping("register")
    public R<?> register(@RequestBody RegisterBody registerBody) throws Exception {
        // 用户注册
        sysLoginService.register(registerBody.getUsername(), RsaUtils.decryptByPrivateKey(registerBody.getPassword()));
        return R.ok();
    }

    @Operation(summary ="手机号登录")
    @PostMapping("mobileLogin")
    public R<?> mobileLogin(@RequestBody LoginBody form)
    {
        // 手机号登录
        LoginUser userInfo = sysLoginService.mobileLogin(form.getPhone(), form.getSmsCode());
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }

    @PostMapping("sendSms")
    @Operation(summary ="发送短信")
    public R<?> sendSms(@RequestParam String phone){
        // 发送短信验证码
        return sysLoginService.sendSms(phone);
    }


    @PostMapping("resetPassword")
    @Operation(summary ="找回密码")
    public R<?> resetPassword(@RequestBody ResetBody form) throws Exception {
        //找回密码
        String password = RsaUtils.decryptByPrivateKey(form.getPassword());
        String rePassword = RsaUtils.decryptByPrivateKey(form.getRePassword());
        return sysLoginService.resetPassword(form.getPhone(), form.getSmsCode(),
                password, rePassword);
    }
}
